//The MIT License
//
//Copyright (c) 2009 nodchip
//
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in
//all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//THE SOFTWARE.
package tv.dyndns.kishibe.client.creation;

import java.util.HashSet;
import java.util.Set;

public class CheckerSlot extends Checker {
	public CheckerSlot(PanelProblemCreation panelProblemCreation) {
		super(panelProblemCreation);
	}

	protected boolean check(WidgetProblemForm form) {
		boolean result = super.check(form);

		if (form.getNumberOfAnswers() < 4) {
			result = false;
			warn("選択肢の数が足りません");
		} else {
			final String[] answers = new String[4];
			final int[] lengthsOfAnswer = new int[4];

			for (int i = 0; i < 4; ++i) {
				answers[i] = form.getTextBoxAnswer(i);
				lengthsOfAnswer[i] = answers[i].length();
			}

			for (int i = 1; i < 4; ++i) {
				if (lengthsOfAnswer[0] != lengthsOfAnswer[i]) {
					result = false;
					warn("解答の長さがそろっていません");
					break;
				}
			}

			if (lengthsOfAnswer[0] < 2) {
				result = false;
				warn("解答の文字数が足りません(2文字以上必要です)");
			} else if (lengthsOfAnswer[0] > 6) {
				result = false;
				warn("解答の文字数が多すぎます(6文字以下である必要があります)");
			}

			final Set<Integer> duplicateColums = new HashSet<Integer>();
			for (int rowFrom = 0; rowFrom < 4; ++rowFrom) {
				for (int rowTo = rowFrom + 1; rowTo < 4; ++rowTo) {
					for (int column = 0; column < Math.min(lengthsOfAnswer[rowFrom], lengthsOfAnswer[rowTo]); ++column) {
						if (answers[rowFrom].charAt(column) == answers[rowTo].charAt(column)) {
							duplicateColums.add(column);
						}
					}
				}
			}

			if (duplicateColums.size() != 0) {
				result = false;
				for (int duplicateColum : duplicateColums) {
					warn((duplicateColum + 1) + "文字目の縦列に重複している文字があります");
				}
			}
		}

		return result;
	}
}
